'use strict';

const Controller = require('egg').Controller;

class CommentController extends Controller {
  async getCommentList() {
    const { ctx } = this;
    const essayId = ctx.params.id;
    const userId = ctx.state.user.id;
    const { list } = await ctx.service.comment.getCommentList(essayId, userId);
    return ctx.helper.success({
      ctx,
      data: list,
    });
  }

  async addComment() {
    const { ctx } = this;
    const commentRule = {
      essay_id: 'number',
      reply_comment_id: 'number',
      content: 'string',
      reply_user_id: 'number',
    };
    const data = ctx.request.body;
    ctx.validate(commentRule, data);
    const userId = ctx.state.user.id;
    data.user_id = userId;
    const { id } = await ctx.service.comment.addComment(data);
    return ctx.helper.success({
      ctx,
      data: { id },
    });
  }

  async deleteComment() {
    const { ctx } = this;
    const commentId = ctx.params.id;
    const userId = ctx.state.user.id;
    const { deleteSuccess } = await ctx.service.comment.deleteComment(commentId, userId);
    return ctx.helper.success({
      ctx,
      msg: deleteSuccess ? '删除评论成功' : '删除评论失败',
    });
  }

  async likeComment() {
    const { ctx } = this;
    const commentId = ctx.params.id;
    const userId = ctx.state.user.id;
    const { insertSuccess } = await ctx.service.comment.likeComment(commentId, userId);
    return ctx.helper.success({
      ctx,
      msg: insertSuccess ? '点赞成功' : '点赞失败',
    });
  }

  async dislikeComment() {
    const { ctx } = this;
    const commentId = ctx.params.id;
    const userId = ctx.state.user.id;
    const { deleteSuccess } = await ctx.service.comment.dislikeComment(commentId, userId);
    return ctx.helper.success({
      ctx,
      msg: deleteSuccess ? '取消点赞成功' : '取消点赞失败',
    });
  }
}

module.exports = CommentController;
